package com.zj.roseoj.judge.judgeservice.impl;

import cn.hutool.json.JSONUtil;
import com.zj.roseoj.common.ErrorCode;
import com.zj.roseoj.exception.BusinessException;
import com.zj.roseoj.judge.codesandbox.CodeSandBoxFactory;
import com.zj.roseoj.judge.codesandbox.CodeSandBoxProxy;
import com.zj.roseoj.judge.codesandbox.CodeSandbox;
import com.zj.roseoj.judge.codesandbox.model.ExecuteCodeRequest;
import com.zj.roseoj.judge.codesandbox.model.ExecuteCodeResponse;
import com.zj.roseoj.judge.judgeservice.JudgeService;
import com.zj.roseoj.judge.strategy.JudgeContext;
import com.zj.roseoj.judge.strategy.JudgeManager;
import com.zj.roseoj.model.dto.question.JudgeCase;
import com.zj.roseoj.model.dto.questionsumbit.JudgeInfo;
import com.zj.roseoj.model.entity.Question;
import com.zj.roseoj.model.entity.QuestionSubmit;
import com.zj.roseoj.model.enums.QuestionSubmitEnum;
import com.zj.roseoj.service.QuestionService;
import com.zj.roseoj.service.QuestionSubmitService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService {

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionSubmitService questionSubmitService;

    @Resource
    private JudgeManager judgeManager;

    @Value("${codeSandBox.type:example}")
    private String codeSandBoxType;

    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        //1.根据传入题目提交ID，获取到对应的题目提交信息和题目信息
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if (questionSubmit == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"提交信息不存在");
        }
        long questionId = questionSubmit.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目不存在");
        }

        //2.根据题目提交状态进行判题，只有待判题状态才判题
        if (!questionSubmit.getStatus().equals(QuestionSubmitEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目正在判题");
        }

        //3.如果是待判题状态则把状态改为判题中，防止用户多次提交，相当于加个锁
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitEnum.RUNNING.getValue());
        boolean update = questionSubmitService.updateById(questionSubmitUpdate);
        if (!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"判题状态更新失败");
        }

        //4.调用代码沙箱，获得执行结果
        CodeSandbox codeSandbox = CodeSandBoxFactory.newInstance(codeSandBoxType);
        CodeSandBoxProxy codeSandBoxProxy = new CodeSandBoxProxy(codeSandbox);
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        String judgeCaseStr = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr,JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();
        ExecuteCodeResponse executeCodeResponse = codeSandBoxProxy.executeCode(executeCodeRequest);

        //5.根据沙箱的执行结果，判断做题是否正确，并设置题目信息
        List<String> outputList = executeCodeResponse.getOutputList();
        //策略设计模式，因为每种语言的判题策略不同
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setQuestion(question);
        judgeContext.setJudgeCaseList(judgeCaseList);
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);

        //6.修改数据库中的判题结果
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitEnum.SUCCEED.getValue());//这里仅仅只是判题过程成功，而不是答案正确
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        update = questionSubmitService.updateById(questionSubmitUpdate);
        if (!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"判题状态更新失败");
        }
        QuestionSubmit questionSubmitResponse = questionSubmitService.getById(questionSubmitId);
        return questionSubmitResponse;
    }
}
